﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.IO;
using System.Configuration;

using FundSms.SmsLib;
using FundSms.Server.Model;
using PersistenceObject.Framework;
using PersistenceObject.Framework.Expressions;

namespace FundSms.RemoteObject
{
    public class RemoteObject : System.MarshalByRefObject
    {
        public static readonly string DataKey = "Sms";
        private static int Debug = 1;

        private static bool LogToFile = ConfigurationManager.AppSettings["LogToFile"] == "1" ? true : false;
        //服务所在路径
        private static string ServicePath = Application.ExecutablePath;
        private static string ServiceDirectory = Path.GetDirectoryName(ServicePath);

        public RemoteObject()
        {
           
        }

        /// <summary>
        /// 用户登陆
        /// </summary>
        /// <param name="enterprisecode">企业号</param>
        /// <param name="enterpriseaccount">企业帐号</param>
        /// <param name="enterprisepassword">企业密码</param>
        /// <param name="ip">客户端IP地址</param>
        /// <param name="mac">客户端MAC地址</param>
        /// <returns>登录状态</returns>
        public int Login(string enterprisecode, string enterpriseaccount, string enterprisepassword,string ip,string mac)
        {
            Enterprise enter = null;

            try
            {
                enter = QueryOperate<Enterprise>.Create(DataKey).Where(
                    Enterprise._EnterpriseCode == enterprisecode
                    &
                    Enterprise._Account == enterpriseaccount
                    &
                    Enterprise._Password == enterprisepassword
                ).Get();
            }
            catch
            {
                return -100;
            }

            if (enter == null)
            {
                //企业号，企业帐号，企业密码不匹配
                return -1;
            }

            if (enter.EnterpriseStatus.ToLower() == "stop")
            {
                //帐号已经被停用
                return -2;
            }

            if (!string.IsNullOrEmpty(enter.IP))
            {
                if (string.IsNullOrEmpty(ip))
                {
                    //IP校验失败
                    return -3;
                }

                if (ip.IndexOf(enter.IP) < 0)
                {
                    //IP地址不正确
                    return -4;
                }
            }

            if (!string.IsNullOrEmpty(enter.MAC))
            {
                if (string.IsNullOrEmpty(mac))
                {
                    //mac校验失败
                    return -5;
                }

                if (mac.IndexOf(enter.MAC) < 0)
                {
                    //MAC地址不正确
                    return -6;
                }
            }

            return 1;
        }

        /// <summary>
        /// 发送数据
        /// </summary>        
        /// <param name="enterprisecode">企业号</param>
        /// <param name="enterpriseaccount">企业帐号</param>
        /// <param name="zipstring">发送的压缩数据</param>
        /// <returns></returns>
        public string Send(string enterprisecode,string enterpriseaccount, string zipstring)
        {
            string unzipedstring = string.Empty;
            enterpriseaccount = enterpriseaccount.ToUpper();

            try
            {
                unzipedstring = Compress.UnzipString(zipstring);
            }
            catch(Exception e)
            {
                Output("解压缩失败：" + e.Message + "\r\n" + e.StackTrace);

                return string.Empty;
            }

            string[] arrsms = Regex.Split(unzipedstring, "\n");

            MT_TEST mt;

            StringBuilder sb = new StringBuilder();

            int j = 0;

            for (int i = 0; i < arrsms.Length; i++)
            {
                string[] arr = arrsms[i].Split(new char[] { '|' });

                mt = new MT_TEST();
                mt.ChannelCode = string.Empty;
                mt.Content = StringEX.ConvertDesSpecialCharacter(arr[2]);
                mt.CreateDate = DateTime.Now;
                mt.EnterpriseCode = enterprisecode;
                mt.LastUpdate = DateTime.Now;
                mt.LogCode = string.Empty;
                mt.Mobile = arr[1];
                mt.MobileType = arr[8];
                mt.Priority = arr[3];
                mt.Ready1 = string.Empty;
                mt.Ready2 = string.Empty;
                mt.Ready3 = string.Empty;
                mt.IsReturn = false;
                mt.IsReport = false;
                mt.Ready4 = 0;
                mt.Ready5 = false;
                mt.Seed = Convert.ToInt32(arr[9]);
                mt.SmsID = arr[6];
                mt.SmsStatus = 0;
                mt.SubID = arr[4];
                mt.SmsStatusRemark = string.Empty;

                try
                {
                    InsertOperate<MT_TEST>.Create(DataKey).From(new Table("SMS_MT_" + enterpriseaccount)).Execute(mt);

                    sb.Append(arr[0] + ",");

                    j++;
                }
                catch (Exception e)
                {
                    Output("插入数据失败：" + e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red);
                }
            }

            #region cancel
            /*
            using (DataSession ds = new DataSession(DataKey))
            {
                try
                {
                    ds.Open();
                    ds.BeginTran();

                    foreach (MT_TEST mttemp in mts)
                    {
                        InsertOperate<MT_TEST>.Create().From(new Table("MM_BBT1")).Execute(mt, ds);
                    }

                    ds.Commit();
                }
                catch (Exception ex)
                {
                    try { ds.RollBack(); }
                    catch { }
                }

            }
            */
            #endregion

            string result = sb.ToString();

            if (result != string.Empty)
            {
                result = result.Substring(0, result.Length - 1);
            }

            Output("接收" + enterpriseaccount + " " + arrsms.Length + " 条数据，成功 " + j.ToString() + " 数据");

            if (result != string.Empty)
            {
                return Compress.ZipString(result);
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 获得短信发送状态，以压缩后的字符窜格式返回
        /// </summary>
        /// <param name="enterprisecode">企业编号</param>
        /// <param name="enterpriseaccount">企业帐号</param>
        /// <param name="rownum">每次返回数据数</param>
        /// <returns>已获得状态的短信数据</returns>
        public string GetSmsStatus(string enterprisecode, string enterpriseaccount, int rownum)
        {
            StringBuilder sb = new StringBuilder();

            IList<MT_TEST> list = null;

            try
            {

                if (rownum == 0)
                {
                    list = QueryOperate<MT_TEST>.Create(DataKey).From(new Table("SMS_MT_" + enterpriseaccount)).Where((MT_TEST._SmsStatus == 2 | MT_TEST._SmsStatus == -1) & MT_TEST._IsReturn == false).OrderBy(MT_TEST._LogID).List();
                }
                else
                {
                    list = QueryOperate<MT_TEST>.Create(DataKey).From(new Table("SMS_MT_" + enterpriseaccount)).Where((MT_TEST._SmsStatus == 2 | MT_TEST._SmsStatus == -1) & MT_TEST._IsReturn == false).OrderBy(MT_TEST._LogID).Top(rownum).List();
                }

            }
            catch (Exception e)
            {
                Output("[" + enterpriseaccount + "]" + e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red);

                return string.Empty;
            }

            if (list.Count > 0)
            {
                int i = 1;

                foreach (MT_TEST test in list)
                {
                    //如果失败则返回错误原因
                    if (test.SmsStatus == -1)
                    {
                        sb.Append(test.LogID + "|" + test.SmsID + "|" + test.Mobile + "|" + test.SmsStatusRemark);
                    }
                    else
                    {
                        sb.Append(test.LogID + "|" + test.SmsID + "|" + test.Mobile + "|0");
                    }

                    //UpdateOperate<MT_TEST>.Create(DataKey).From(new Table("SMS_MT_" + enterpriseaccount)).Fields(FieldValue.Create(MT_TEST._IsReturn, true)).Where(MT_TEST._LogID == test.LogID);

                    if (i < list.Count)
                    {
                        sb.Append("\n");
                    }

                    i++;
                }
            }

            list.Clear();
            list = null;

            string result = sb.ToString();

            sb = null;

            return Compress.ZipString(result);

        }

        /// <summary>
        /// 更新服务器端短信状态为客户端已经接收
        /// </summary>
        /// <param name="enterprisecode"></param>
        /// <param name="enterpriseaccount"></param>
        /// <param name="idlist"></param>
        /// <returns></returns>
        public void UpdateSmsStatus(string enterprisecode, string enterpriseaccount, string idlist)
        {
            string list = Compress.UnzipString(idlist);
            string[] arr = Regex.Split(list, ",");

            for (int i = 0; i < arr.Length; i++)
            {
                try
                {
                    UpdateOperate<MT_TEST>.Create(DataKey).From(new Table("SMS_MT_" + enterpriseaccount)).Fields(FieldValue.Create(MT_TEST._IsReturn, true), FieldValue.Create(MT_TEST._LastUpdate, DateTime.Now)).Where(MT_TEST._LogID == Convert.ToInt32(arr[i])).Execute();
                }
                catch (Exception e)
                {
                    Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red);
                }
            }
        }

        /// <summary>
        /// 获得企业上行信息
        /// </summary>
        /// <param name="enterprisecode"></param>
        /// <param name="enterpriseaccount"></param>
        /// <returns></returns>
        public string GetMO(string enterprisecode, string enterpriseaccount)
        {
            IList<MO> list = null;

            try
            {
                list = QueryOperate<MO>.Create(DataKey).From(new Table("SMS_MO")).Where(MO._EnterpriseCode == enterprisecode & MO._Status == 0).OrderBy(MO._LogID).List();
            }
            catch (Exception e)
            {
                Output( "[" + enterpriseaccount + "]" + e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red);

                return string.Empty;
            }

            StringBuilder sb = new StringBuilder();

            if (list.Count > 0)
            {
                int i = 1;

                foreach (MO mo in list)
                {
                    sb.Append(mo.LogID + "|" + mo.Mobile + "|" + mo.ServiceCode + "|" + StringEX.ConvertOriSpecialCharacter(mo.Content) + "|" + mo.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"));

                    if (i < list.Count)
                    {
                        sb.Append("\n");
                    }

                    i++;
                    
                }
            }

            list.Clear();
            list = null;

            string result = sb.ToString();

            sb = null;

            return Compress.ZipString(result);

        }

        /// <summary>
        /// 更新短信上行状态
        /// </summary>
        /// <param name="enterprisecode"></param>
        /// <param name="enterpriseaccount"></param>
        /// <param name="idlist"></param>
        public void UpdateMO(string enterprisecode, string enterpriseaccount, string idlist)
        {
            string list = Compress.UnzipString(idlist);
            string[] arr = Regex.Split(list, ",");

            for (int i = 0; i < arr.Length; i++)
            {
                try
                {
                    UpdateOperate<MO>.Create(DataKey).From(new Table("SMS_MO")).Fields(FieldValue.Create(MO._Status, 1)).Where(MO._LogID == Convert.ToInt32(arr[i])).Execute();
                }
                catch (Exception e)
                {
                    Output("[" + enterpriseaccount + "]" + e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red);
                }
            }
        }

        /// <summary>
        /// 获得指定企业的黑名单
        /// </summary>
        /// <param name="enterprisecode"></param>
        /// <returns></returns>
        public string GetBlackList(string enterprisecode)
        {
            IList<BlackList> list = null;

            try
            {
                list = QueryOperate<BlackList>.Create(DataKey).From(new Table("SMS_BlackList")).Where(BlackList._EnterpriseCode == enterprisecode).List();
            }
            catch (Exception e)
            {
                Output("[" + enterprisecode + "]" + e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red);

                return string.Empty;
            }

            StringBuilder sb = new StringBuilder();

            if (list.Count > 0)
            {
                foreach (BlackList black in list)
                {
                    sb.Append(black.Mobile + ",");
                }
            }

            list.Clear();
            list = null;

            string result = sb.ToString();

            sb = null;

            if (result != string.Empty)
            {
                result = result.Substring(0, result.Length - 1);

                return Compress.ZipString(result);
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 获得所有的黑名单
        /// </summary>
        /// <param name="enterprisecode"></param>
        /// <returns></returns>
        public string GetBlackList()
        {
            IList<BlackListGlobal> list = null;

            try
            {
                list = QueryOperate<BlackListGlobal>.Create(DataKey).From(new Table("SMS_BlackListGlobal")).List();
            }
            catch (Exception e)
            {
                Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red);

                return string.Empty;
            }

            StringBuilder sb = new StringBuilder();

            if (list.Count > 0)
            {
                foreach (BlackListGlobal black in list)
                {
                    sb.Append(black.Mobile + ",");
                }
            }

            list.Clear();
            list = null;

            string result = sb.ToString();

            sb = null;

            if (result != string.Empty)
            {
                result = result.Substring(0, result.Length - 1);

                return Compress.ZipString(result);
            }
            else
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 获得所有的屏蔽关键字
        /// </summary>
        /// <returns></returns>
        public string GetKeyWords()
        {
            IList<KeyWords> list = null;

            try
            {
                list = QueryOperate<KeyWords>.Create(DataKey).From(new Table("SMS_KeyWords")).List();
            }
            catch (Exception e)
            {
                Output(e.Message + "\r\n" + e.StackTrace, ConsoleColor.Red);

                return string.Empty;
            }

            StringBuilder sb = new StringBuilder();

            if (list.Count > 0)
            {
                foreach (KeyWords key in list)
                {
                    sb.Append(key.KeyWord + ",");
                }
            }

            list.Clear();
            list = null;

            string result = sb.ToString();

            sb = null;

            if (result != string.Empty)
            {
                result = result.Substring(0, result.Length - 1);

                return Compress.ZipString(result);
            }
            else
            {
                return string.Empty;
            }
        }


        ~RemoteObject()
        {
            Output("销毁服务器端程序");
        }

        #region 调试辅助逻辑
        private static string GetDateTime()
        {
            return "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
        }

        private static void Output(string msg)
        {
            if (Debug == 1)
            {
                Console.WriteLine(GetDateTime() + msg);
            }
        }

        private static void Output(string msg, ConsoleColor color)
        {
            if (Debug == 1)
            {
                Console.ForegroundColor = color;
                Console.WriteLine(GetDateTime() + msg);
                Console.ResetColor();
            }
        }
        #endregion
    }
}
